package com.cims.dao.task;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.cims.common.exception.DaoException;
import com.cims.common.vo.Staff;
import com.cims.common.vo.Task;
import com.cims.dao.hibernate.HibernateUtil;

;
public class TaskDAOImpl implements TaskDAO {

	@Override
	public List<Task> getListTask() throws DaoException {
		return HibernateUtil.selectAll(Task.class);
	}

	@Override
	public Task findByTaskId(int taskId) throws DaoException {
		return HibernateUtil.findByID(Task.class, taskId);
	}

	@Override
	public List<Task> getListTaskByStaffId(int staffId) throws DaoException {
		List<Task> lstVo = null;
		SessionFactory factory = HibernateUtil.getSessionFactory();
		Session session = null;

		try {
			session = factory.openSession();

			Query query = session
					.createQuery("from Task as T where T.staff.staffId = :staffId");
			query.setParameter("staffId", staffId);
			lstVo = query.list();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}

		return lstVo;
	}

	@Override
	public List<Task> getTodayListTaskByStaffId(int staffId) {
		List<Task> lstVo = null;
		SessionFactory factory = HibernateUtil.getSessionFactory();
		Session session = null;

		try {
			session = factory.openSession();
			// Get today
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			Date dateNow = new Date();
			String datePara = "'" + dateFormat.format(dateNow) + "'";
			
			
			
			Query query = session
					.createQuery("from Task as T where T.staff.staffId = "
							+ staffId + " and T.orderItem.dateStart = "
							+ datePara);
			// query.setParameter("staffId", staffId);
			// query.setParameter("date", new Date());

			lstVo = query.list();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}

		return lstVo;
	}

	@Override
	public boolean insert(Task task) throws DaoException {
		//return HibernateUtil.insertVo(task);
		
		SessionFactory factory = HibernateUtil.getSessionFactory();
		Session session = null;

		try {
			session = factory.openSession();
			Transaction tx = session.beginTransaction();
			 SQLQuery query = session
					.createSQLQuery("insert into Task(StaffId, OrderId) values('" + task.getStaff().getStaffId() + "', '" + task.getOrderItem().getOrderId() + "')");
			query.executeUpdate();
			tx.commit();
			return true;
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		
		return false;

	}
}
